import numpy as np
import paho.mqtt.client as mqtt
from sklearn.naive_bayes import GaussianNB

from 光照.dataset import LightDataset

# 定义模型
train_dataset = LightDataset()
category_name = train_dataset.get_category_name()
X, y = train_dataset.get_data()
nb = GaussianNB()
nb.fit(X, y)

# 定义mqtt
# MQTT服务器地址
broker_address = "192.168.10.29"  # 替换为你的MQTT代理地址
port = 1883  # MQTT代理的端口，默认为1883
client_id = "python_mqtt_client"  # MQTT客户端的唯一ID

messages = []

# 当连接到MQTT代理时调用的回调函数
def on_connect(client, userdata, flags, reason_code, properties):
    print(f"Connected with result code {reason_code}")
    # 订阅主题
    client.subscribe("base/light")


# 当接收到MQTT消息时调用的回调函数
def on_message(client, userdata, msg):
    light = msg.payload.decode('utf-8')
    # 收集最近的十条信息，送去判断分类
    if len(messages) == 10:
        messages.remove(messages[0])
        messages.append(light)
        data = np.array([messages],dtype=np.float32)
        # 送去预测结果
        result:int = int(nb.predict(data)[0])
        print(category_name[result])
        client.publish("base/light_status", result)
    else:
        messages.append(light)

# 创建MQTT客户端实例
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)

# 为客户端设置回调函数
client.on_connect = on_connect
client.on_message = on_message

# 连接到MQTT代理
client.connect(broker_address, port)
if __name__ == '__main__':
    # 将预测结果发送给MQTT,实时显示结果
    # 开始网络循环，处理接收到的消息和重连
    client.loop_forever()
